 package com.yangguo.code.generator.util;

 import java.util.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import lombok.extern.slf4j.Slf4j;

@Slf4j
 public class EncryptionUtil {

     public static String encrypt(String param, String dataKey) {
         try {
             SecretKeySpec keySpec = new SecretKeySpec(dataKey.getBytes(), "AES");
             Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
             cipher.init(Cipher.ENCRYPT_MODE, keySpec);

             byte[] encryptedData = cipher.doFinal(param.getBytes());

             String base64Encrypted = Base64.getEncoder().encodeToString(encryptedData);

             return base64Encrypted.replace("+", "*").replace("/", "-").replace("=", "");
         } catch (Exception e) {
             log.error("加密失败", e);
         }
         return "";
     }

     public static String decrypt(String encryptedParam, String dataKey) throws Exception {
         // 还原替换的字符
         String replacedParam = encryptedParam.replace("*", "+").replace("-", "/");
         // 根据 Base64 编码的特性，补齐缺失的 '='
         while (replacedParam.length() % 4 != 0) {
             replacedParam = replacedParam + "=";
         }

         // 进行 Base64 解码
         byte[] decodedData = Base64.getDecoder().decode(replacedParam);

         // 创建 AES 密钥规范
         SecretKeySpec keySpec = new SecretKeySpec(dataKey.getBytes(), "AES");
         // 获取 Cipher 实例，使用 AES/ECB/PKCS5Padding 模式
         Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
         // 初始化解密模式
         cipher.init(Cipher.DECRYPT_MODE, keySpec);

         // 执行解密操作
         byte[] decryptedData = cipher.doFinal(decodedData);

         // 将解密后的字节数组转换为字符串
         return new String(decryptedData);
     }

     public static void main(String[] args) throws Exception {
         String param = "{\"name\":\"sss\"}";
         String dataKey = "e115dfc1a0d24d04"; // 16 字节的密钥


         JSONObject myJson = (JSONObject)JSON.parse(My.getData());
         System.out.println("JT密文数据: " + myJson.getString("data"));

         String jtDecryptedParam = My.decrypt(myJson.getString("data"), dataKey);
         System.out.println("JT解密数据: " + jtDecryptedParam);

         // 加密
         String encryptedParam = encrypt(jtDecryptedParam, dataKey);
         System.out.println("XC加密后的数据: " + encryptedParam);
         String decryptedParam = decrypt(encryptedParam, dataKey);
         System.out.println("XC解密数据: " + decryptedParam);

     }
 }